package com.xlf.common.core.util;


import cn.hutool.core.io.FileUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class CommandUtil {
    public static int run(File workingDirectory,List cmd, String stdoutFilePath, String stderrFilePath,String input){
        try {
            Process process = new ProcessBuilder(cmd)
                    .directory(workingDirectory)
                    .start();
            OutputStream outputStream = process.getOutputStream();
            if(StringUtils.isNotEmpty(input))
                outputStream.write(input.getBytes());
            if(stdoutFilePath != null){
                // 获取运行的标准输出
                InputStream stdoutFrom = process.getInputStream();

                // 将标准输出写入到文件中
                FileUtil.writeFromStream(stdoutFrom,stdoutFilePath);
            }
            if(stderrFilePath != null){

//                // 获取运行的标准错误
                InputStream stderrFrom = process.getErrorStream();

//                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//                byte[] buffer = new byte[4096];
//                int bytesRead;
//                while ((bytesRead = stderrFrom.read(buffer)) != -1) {
//                    byteArrayOutputStream.write(buffer, 0, bytesRead);
//                }
//                byte[] inputData = byteArrayOutputStream.toByteArray();
//
//                System.out.println(inputData.toString());
//                // 将标准错误写入到文件中
                FileUtil.writeFromStream(stderrFrom,stderrFilePath);
            }
            // 等到子进程结束，拿到子进程的状态码，并返回
            int exitCode = process.exitValue();
            return exitCode;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1;
    }

//    public static void main(String[] args) {
//        run("javac","E://stdout.txt","E://stderr.txt");
//    }
}
